package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxReturnList;
import com.adk.backend.mapper.ReturnMapper;
import com.adk.backend.service.ReturnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 退货服务实现类
 */
@Slf4j
@Service
public class ReturnServiceImpl extends ServiceImpl<ReturnMapper, LxReturnList> implements ReturnService {
    
    @Autowired
    private ReturnMapper returnMapper;
    
    @Override
    public PageResult<Map<String, Object>> getReturnList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        // 计算偏移量
        Integer offset = (pageNum - 1) * pageSize;
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        
        // 查询总数
        Long total = returnMapper.countReturnList(params);
        
        // 查询列表
        List<Map<String, Object>> list = returnMapper.selectReturnListWithInfo(params);
        
        PageResult<Map<String, Object>> result = new PageResult<>();
        result.setList(list);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotalPages((int) Math.ceil((double) total / pageSize));
        
        return result;
    }
    
    @Override
    public LxReturnList getReturnById(Long id) {
        return returnMapper.selectById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxReturnList createReturn(LxReturnList returnList) {
        if (returnList.getAddTime() == null) {
            returnList.setAddTime((int) (System.currentTimeMillis() / 1000));
        }
        returnMapper.insert(returnList);
        return returnList;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReturn(LxReturnList returnList) {
        // lx_return_list 表没有 update_time 字段，所以不需要设置更新时间
        return returnMapper.updateById(returnList) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteReturn(Long id) {
        return returnMapper.deleteById(id) > 0;
    }
}

